package file

import (
	"context"
	"fmt"
	"os"
	"path"
	"strconv"
	"strings"
	"time"

	"mall/common/globalkey"
	"mall/common/modelx"
	"mall/service/attachment/model"
	"mall/service/attachment/rpc/internal/svc"
	"mall/service/attachment/rpc/internal/utils/errorhandler"
	"mall/service/attachment/rpc/types/attachment"
	"mall/service/backend/common/errorx"
	"mall/service/backend/common/i18n"

	// "github.com/sirupsen/logrus"
	"github.com/volatiletech/null/v8"
	"github.com/zeromicro/go-zero/core/logx"
)

type BackendUpdateFileLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewBackendUpdateFileLogic(ctx context.Context, svcCtx *svc.ServiceContext) *BackendUpdateFileLogic {
	return &BackendUpdateFileLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *BackendUpdateFileLogic) BackendUpdateFile(in *attachment.FileInfo) (*attachment.BaseResp, error) {
	if len(in.Ids) > 0 {
		tx, err := l.svcCtx.DB.BeginTx(l.ctx, nil)
		if err != nil {
			return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
		}

		now := time.Now()
		for _, id := range in.Ids {
			if id > 0 {
				file, err := l.svcCtx.MediaFile.FindOneNoCache(l.ctx, tx, id)
				if err != nil {
					tx.Rollback()
					return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
				}

				if in.Status != nil {
					file.PostStatus = uint16(*in.Status)
				}
				file.PostModifiedDate = now
				err = l.svcCtx.MediaFile.Update(l.ctx, tx, file, nil)
				if err != nil {
					tx.Rollback()
					return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
				}
			}
		}

		tx.Commit()

		return &attachment.BaseResp{
			Msg: i18n.UpdateSuccess,
		}, nil
	}

	if in.Id == nil || len(*in.Id) == 0 {
		return nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
	}

	var id uint64
	if i, err := strconv.ParseInt(*in.Id, 10, 64); err == nil {
		id = uint64(i)
	} else {
		return nil, errorx.NewInvalidArgumentError(i18n.ValidationError)
	}

	file, err := l.svcCtx.MediaFile.FindOneNoCache(l.ctx, nil, id)
	if err != nil {
		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
	}

	var originalPath string = file.Path
	if file.PostType == uint16(globalkey.AttachmentTypeDirectory) {
		var parentId uint64
		if in.ParentId != nil {
			parentId = *in.ParentId
		} else {
			parentId = file.PostParentID
		}
		if parentId == 0 {
			parentId = l.svcCtx.Config.NfsConf.UploadsId
		}
		parentDir, err := l.svcCtx.MediaFile.FindOne(l.ctx, parentId)
		if err != nil {
			return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
		}

		parentPath := parentDir.Path
		if in.Filename != nil {
			file.PostName = strings.ToLower(strings.TrimSpace(*in.Filename))
		}
		if in.Path != nil {
			file.Path = strings.ToLower(strings.TrimSpace(*in.Path))
		} else if len(file.Path) == 0 && len(file.PostName) > 0 {
			file.Path = strings.ToLower(fmt.Sprintf("%s/%s", parentPath, file.PostName))
		}
		if len(file.Path) == 0 {
			logx.Errorw("update media directory failed, its path is required")
			return nil, errorx.NewInvalidArgumentError("file.directoryPathRequired")
		}

		filterMap := make(map[string]map[string][]any)
		filterMap[model.AttachmentColumns.Path] = map[string][]any{
			"equalTo": []any{file.Path},
		}
		filterMap[model.AttachmentColumns.PostParentID] = map[string][]any{
			"equalTo": []any{parentId},
		}
		list, _, err := l.svcCtx.MediaFile.GetList(l.ctx, model.M{
			"pageSize": uint64(2),
			"select":   ",",
		}, -1, filterMap)
		if err != nil {
			return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
		}

		count := len(list)
		if count > 1 {
			return nil, errorx.NewAlreadyExistsError("file.directoryPathAlreadyExists")
		}

		if count == 1 && list[0].ID != id {
			return nil, errorx.NewAlreadyExistsError("file.directoryPathAlreadyExists")
		}

		file.PostParentID = parentId
		if in.AltText != nil {
			file.PostTitle = strings.TrimSpace(*in.AltText)
		}
		if in.Excerpt != nil {
			file.PostExcerpt = strings.TrimSpace(*in.Excerpt)
		}
		err = l.svcCtx.MediaFile.Update(l.ctx, nil, file, nil)
		if err != nil {
			return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
		}

		if originalPath != file.Path {
			originalDir := path.Join(l.svcCtx.Config.NfsConf.PathPrefix, originalPath)
			dir := path.Join(l.svcCtx.Config.NfsConf.PathPrefix, file.Path)
			err = os.Rename(originalDir, dir)
			if err != nil {
				logx.Errorw("fail to change the path of directory", logx.Field("detail", err.Error()))
				return nil, err
			}
		}

		return &attachment.BaseResp{
			Msg: i18n.UpdateSuccess,
		}, nil
	}

	if in.Filename != nil {
		file.PostName = strings.TrimSpace(*in.Filename)
	}
	if in.Path != nil {
		file.Path = strings.TrimSpace(*in.Path)
	}
	if in.Size != nil {
		file.Size = *in.Size
	}
	if in.Type != nil {
		file.PostType = uint16(*in.Type)
	}
	if in.MimeType != nil {
		file.PostMimeType = strings.TrimSpace(*in.MimeType)
	}
	if in.Md5 != nil {
		file.MD5 = strings.TrimSpace(*in.Md5)
	}
	if in.ParentId != nil && *in.ParentId > 0 {
		file.PostParentID = *in.ParentId
	}
	if file.PostParentID == 0 {
		file.PostParentID = l.svcCtx.Config.NfsConf.UploadsId
	}
	if in.AltText != nil {
		file.PostTitle = strings.TrimSpace(*in.AltText)
	}
	if in.Excerpt != nil {
		file.PostExcerpt = strings.TrimSpace(*in.Excerpt)
	}
	var originalStatus uint16
	var status uint16
	if in.Status != nil {
		originalStatus = file.PostStatus
		status = uint16(*in.Status)
		file.PostStatus = status

		if status > 0 {
			if originalStatus == uint16(globalkey.AttachmentStatusPrivate) && status != uint16(globalkey.AttachmentStatusPrivate) {
				filePath := path.Join(l.svcCtx.Config.NfsConf.PathPrefix, file.Path)
				filePath = strings.Replace(filePath, l.svcCtx.Config.NfsConf.PrivateStorePath, l.svcCtx.Config.NfsConf.PublicStorePath, -1)
				file.Path = strings.TrimPrefix(filePath, l.svcCtx.Config.NfsConf.PathPrefix)
			} else if originalStatus != uint16(globalkey.AttachmentStatusPrivate) && status == uint16(globalkey.AttachmentStatusPrivate) {
				filePath := path.Join(l.svcCtx.Config.NfsConf.PathPrefix, file.Path)
				filePath = strings.Replace(filePath, l.svcCtx.Config.NfsConf.PublicStorePath, l.svcCtx.Config.NfsConf.PrivateStorePath, -1)
				file.Path = strings.TrimPrefix(filePath, l.svcCtx.Config.NfsConf.PathPrefix)
			}
		}
	}

	now := time.Now() // 本地时间
	gmtNow := modelx.GetGmtTime(now)
	file.PostModifiedDate = now
	file.PostModifiedGMT = gmtNow

	mediaRel := &model.AttachmentRel{}
	if len(in.Meta) > 0 {
		filterMap := make(map[string]map[string][]any)
		filterMap[model.AttachmentMetumColumns.AttachmentID] = map[string][]any{
			"equalTo": []any{id},
		}
		list, _, err := l.svcCtx.MediaFile.GetMeta(l.ctx, model.M{}, -1, filterMap)
		if err != nil {
			return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
		}

		if len(list) > 0 { // 原有的 Meta（决定现有的是增还是改）
			var mids []uint64
			omidMap := make(map[uint64]struct{})
			for _, v := range list {
				mids = append(mids, v.MetaID)
				omidMap[v.MetaID] = struct{}{}
			}

			// 现有的 Meta（决定原有的是删还是留）
			nmidMap := make(map[uint64]struct{})
			for _, v := range in.Meta {
				if v.Key == nil || len(strings.TrimSpace(*v.Key)) == 0 {
					continue
				}

				if v.Value == nil || len(strings.TrimSpace(*v.Value)) == 0 {
					continue
				}

				var metum model.AttachmentMetum
				metum.AttachmentID = id
				metum.MetaKey = strings.TrimSpace(*v.Key)
				metum.MetaValue = null.StringFrom(strings.TrimSpace(*v.Value))

				if v.Id != nil && *v.Id > 0 {
					if _, ok := omidMap[*v.Id]; ok { // 有值且是有效值
						nmidMap[*v.Id] = struct{}{}
						metum.MetaID = *v.Id
					}
				}

				mediaRel.Meta = append(mediaRel.Meta, &metum)
			}

			for _, mid := range mids {
				if _, ok := nmidMap[mid]; !ok { // 当前不存在的值
					mediaRel.DelMetumIds = append(mediaRel.DelMetumIds, mid)
				}
			}
		} else {
			for _, v := range in.Meta {
				if v.Key == nil || len(strings.TrimSpace(*v.Key)) == 0 {
					continue
				}

				if v.Value == nil || len(strings.TrimSpace(*v.Value)) == 0 {
					continue
				}

				var metum model.AttachmentMetum
				metum.AttachmentID = id
				metum.MetaKey = strings.TrimSpace(*v.Key)
				metum.MetaValue = null.StringFrom(strings.TrimSpace(*v.Value))

				mediaRel.Meta = append(mediaRel.Meta, &metum)
			}
		}
	}

	if len(in.CategoryIds) > 0 || len(in.TagIds) > 0 {
		relFilterMap := make(map[string]map[string][]any)
		relFilterMap[model.AttachmentTermRelationshipColumns.ObjectID] = map[string][]any{
			"equalTo": []any{id},
		}
		rel, _, err := l.svcCtx.MediaTerm.GetRelationshipList(l.ctx, model.M{}, -1, relFilterMap)
		if err != nil {
			return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
		}

		if len(rel) > 0 {
			var tids []uint64
			otidMap := make(map[uint64]struct{})
			for _, v := range rel {
				tids = append(tids, v.TermID)
				otidMap[v.TermID] = struct{}{}
			}

			ntidMap := make(map[uint64]struct{})
			for _, tid := range in.CategoryIds {
				if tid == 0 {
					continue
				}

				ntidMap[tid] = struct{}{}
				if _, ok := otidMap[tid]; !ok { // 增TermId
					mediaRel.TermIds = append(mediaRel.TermIds, tid)
				}
			}
			for _, tid := range in.TagIds {
				if tid == 0 {
					continue
				}

				ntidMap[tid] = struct{}{}
				if _, ok := otidMap[tid]; !ok { // 增TermId
					mediaRel.TermIds = append(mediaRel.TermIds, tid)
				}
			}

			for _, tid := range tids {
				if _, ok := ntidMap[tid]; !ok { // 删TermId
					mediaRel.DelTermIds = append(mediaRel.DelTermIds, tid)
				}
			}
		} else {
			for _, tid := range in.CategoryIds {
				if tid > 0 {
					mediaRel.TermIds = append(mediaRel.TermIds, tid)
				}
			}
			for _, tid := range in.TagIds {
				if tid > 0 {
					mediaRel.TermIds = append(mediaRel.TermIds, tid)
				}
			}
		}
	}

	// logrus.Info(fmt.Sprintf("BackendUpdateFile rel: %+v", rel))
	err = l.svcCtx.MediaFile.Update(l.ctx, nil, file, mediaRel)
	if err != nil {
		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
	}

	if originalPath != file.Path {
		originalDir := path.Join(l.svcCtx.Config.NfsConf.PathPrefix, originalPath)
		dir := path.Join(l.svcCtx.Config.NfsConf.PathPrefix, file.Path)
		err = os.Rename(originalDir, dir)
		if err != nil {
			logx.Errorw("fail to change the path of file", logx.Field("detail", err.Error()))
			return nil, err
		}
	}

	return &attachment.BaseResp{
		Msg: i18n.UpdateSuccess,
	}, nil
}
